var generator = require('../generator/generator');
var user = require('../model/user');
var userRole = require('../model/userRole');

exports.select = function(req, res, connection){
  var keyword = req.query.keyword;
  var cpage = req.query.cpage;
  var pageSize = req.query.pageSize;
  var begin = pageSize * (cpage - 1);
  var end = pageSize * cpage -  1;
  user.query(connection, keyword, function(rows) { 
    // console.log('rows',rows);
    var newData = [];
    for(var i = 0; i < rows.length; i ++){//删除重复的数据
      for(var j = i + 1; j < rows.length;){
        if(rows[i].id == rows[j].id){
          rows[i].rid = rows[i].rid + ',' + rows[j].rid;
          rows[i].roleName = rows[i].roleName + ',' + rows[j].roleName;     
          rows.splice(j,1);
        } else {      
          j++;
        }
      }
    }
    // console.log('newData',rows);

    var data = [];
    var k = 0;
    for (var i = begin; i < end + 1; i++) {
      if (i < rows.length) {
        data[k] = rows[i];
        k++;
      }
    }
    var sendData = {
      data: data,
      count: rows.length
    }
    res.send(sendData);
  });
};
exports.selectName = function(req, res, connection){
  var name = req.params['name'];
  user.findOne(connection, name, function(rows){
    res.send(rows);
  });
};

/*
  添加用户
*/
exports.addUser = function(req,res,connection){
  var data = req.body;
  console.log('data:',data);
  user.add(connection,data,function(rows){
    res.send(rows);
  });
};

exports.login = function(req, res){
  if (req.user != null || req.user != undefined) {
    return res.redirect('/desktop');
  } else {
    res.send(generator.generate('login'));
  }
};
/**
 * Show sign up form
 */

exports.signup = function(req, res) {
  res.send(generator.generate('login'));
};

/**
 * Logout
 */


exports.logout = function(req, res) {
  req.logout();
  res.redirect('/login');
};

/**
 * Session
 */

exports.session = function(req, res) {
  return res.redirect('/desktop');
};

exports.check = function(req, res, connection) {
  var data = {
    username: req.body.userName,
    password: req.body.password
  };
  user.findOne(connection, data, function(row) {
    if (row != "")
      res.send("false");
    else
      res.send("true");
  });
};

exports.deleteOne = function(req,res,connection){
  var id = req.query.id;
  //console.info('id::::',id);
  user.delet(connection, id, function(row){
    res.send(row);
  });
};

exports.updateOne = function(req,res,connection){
  var data = req.body;
  //console.info('dataaaassssdd:',data);
  user.update(connection, data, function(rows){
    res.send(rows);
  });
};

exports.changePwd = function(req,res,connection){
  var data = req.body;
  console.info('data',data);
  user.changePwd(connection, data, function(rows){
    res.send(rows);
  });
};

exports.getResource = function(req, res, connection){
  var uid = req.query.uid;
  user.findResource(connection,uid,function(data){
    res.send(data);
  });
};